package com.loie.xcx.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

/**
 * @program: yesfp-demo
 * @description:
 * @author: kw
 * @create: 2020/05/22 10:29
 */
public class Base64Util {

    /**
     * 网络图片转换Base64的方法
     * 单线程处理 若批量可以考虑多线程执行
     *
     * @param netImagePath     
     */
    public static String NetImageToBase64(String netImagePath) {
        final ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(netImagePath);
            final byte[] by = new byte[1024];
            // 创建链接
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            // 关闭流
            is.close();
            return Base64.getEncoder().encodeToString(data.toByteArray());
            //return encoder.encode(data.toByteArray()).replaceAll("\n", "").replaceAll("\r", "");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @description:  本地图片转Base64
     * @author: kw
     * @date: 2020/5/22
     * @param: [imgPath]
     * @return: java.lang.String
     */
    public static String imageToBase64(String imgPath) {
        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 返回Base64编码过的字节数组字符串
        //return new BASE64Encoder().encode(data).replaceAll("\n", "").replaceAll("\r", "");
        return Base64.getEncoder().encodeToString(data);
    }
    //将文件转化为base64;
    public static String encryptToBase64(String filePath)  {
        if (filePath == null) {
            return null;
        }
        try {
//            if (filePath.contains("txt")){
//            byte[] b = Files.readAllBytes(Paths.get(filePath));
//            return Base64.getEncoder().encodeToString(b);}
//            if (filePath.contains("xls")||(filePath.contains("xlsx"){
//                HSSFWorkbook excelWorkBook = new HSSFWorkbook();
//                ExcelUtil.saveToExcel(excelWorkBook, resultlist, tableColnm, sheetName);
//                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//                try {
//                    // 将EXCEL文件写进流内
//                    excelWorkBook.write(byteArrayOutputStream);

            File excelFile = new File(filePath);
            FileInputStream fis = new FileInputStream(excelFile);
            byte[] excelBytes = new byte[(int)excelFile.length()];
            fis.read(excelBytes);
            fis.close();

            // Base64编码
            Base64.Encoder encoder = Base64.getEncoder();
            String base64Excel = encoder.encodeToString(excelBytes);
            return base64Excel;

//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                byte[] bytes = byteArrayOutputStream.toByteArray();
//                String base64ExlCode = Base64Utils.encodeToString(bytes);           }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 将文件输入流转为base64
     */
    public static String getBase64FromInputStream(InputStream in) {
        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;
        // 读取图片字节数组
        try {
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = in.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Base64.getEncoder().encodeToString(data);
    }

    public static Boolean base64ToFile(String destPath,String base64, String fileName) {
        File file = null;
        //创建文件目录
        String filePath=destPath;
        File  dir=new File(filePath);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try {
            byte[] bytes = Base64.getDecoder().decode(base64);
            file=new File(filePath+"/"+fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }



}
